package cn.com.headfree.base.common;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

@Component
public class OSSClientFactory {
	private static final Logger log = Logger.getLogger(OSSClientFactory.class);
	@Value("${oss.pool.size}")
	private int poolSize = 10;
	private BlockingQueue<OSS> blockingQueue;
	@Value("${oss.endpoint}")
	private String endpoint;
	@Value("${oss.accessKeyId}")
	private String accessKeyId;
	@Value("${oss.accessKeySecret}")
	private String accessKeySecret;
	@Value("${oss.queue.wait.timelong}")
	private int queueWaitTimeLong = 30000;
	private static final int WAIT_TIMES=30; 
	
	/**
	 * @description 获取OSS连接对象
	 * @author 冯亚
	 * @date 2020年6月9日 上午10:19:50
	 * @return
	 * @throws InterruptedException
	 * @return OSS
	 */
	public synchronized OSS getOSSClient() throws InterruptedException {
		if (this.blockingQueue == null) {
			this.initQueue();
		}
		log.info("队列大小:" + this.blockingQueue.size());
		int i = 0;
		while (this.blockingQueue.size() == 0) {
			i ++;
//			log.info(fileName + "队列为空，我处于等待状态！");
			this.wait(queueWaitTimeLong/WAIT_TIMES);
			if (i>WAIT_TIMES) {
				break;
			}
		}
		if (this.blockingQueue.size() > 0) {
			OSS oss = this.blockingQueue.take();
//			log.info(fileName + "我从队列中获取了对象！" + oss);
			return oss;
		} else {
			return null;
		}
		
	}

	/**
	 * @description 初始化消息队列，创建若干个OSS对象
	 * @author 冯亚
	 * @date 2020年6月9日 上午10:20:10
	 * @throws InterruptedException
	 * @return void
	 */
	public void initQueue() throws InterruptedException {
		if (this.blockingQueue == null) {
			this.blockingQueue = new ArrayBlockingQueue<OSS>(poolSize);
		}
		OSS ossClient = null;
		for (int i = this.blockingQueue.size(); i < poolSize; i++) {
			ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
			blockingQueue.put(ossClient);
		}
	}
	
	/**
	 * @description 操作完后，释放连接，并创建新的OSS对象放入到消息队列中
	 * @author 冯亚
	 * @date 2020年6月9日 上午10:20:42
	 * @param oss
	 * @throws InterruptedException
	 * @return void
	 */
	public void returnOSS(OSS oss) throws InterruptedException {
//		Thread.sleep(10000);
//		log.info(fileName + "销毁对象");
		oss.shutdown();
//		log.info(fileName + "向队列中添加一个对象");
		if (this.blockingQueue.size() < poolSize) {
			this.blockingQueue.put(new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret));
		}
	}
	
}
